package assist.datastore.dao;

import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import java.util.logging.Logger;

import assist.datastore.Datastore;
import assist.datastore.JDODatastore;
import assist.domain.model.Team;

public class TeamDAO extends EntityDAO<Team> 
{
    private static Logger logger = 
        Logger.getLogger(TeamDAO.class.getName()); 
    protected TeamDAO(Datastore<Team> datastore)
    {
        super(datastore, Team.class);
    }

    public Team getByTeamName(String name)
    {
        PersistenceManager pm = JDODatastore.getPersistenceManager();
        try
        {
            name = name.toUpperCase();
            if (name.equals("CANADIENS MONTREAL"))
            {
                name = "MONTREAL CANADIENS";
            }
            Query query = pm.newQuery(Team.class);
            query.setFilter("nameParam.startsWith(city.toUpperCase()) && nameParam.endsWith(nickname.toUpperCase())");
            query.declareParameters("String nameParam");                      
            query.setUnique(true);
            return pm.detachCopy((Team) query.execute(name));
        }
        finally
        {
            pm.close();
        }
    }

    public Set<Team> getCurrentTeams()
    {
        PersistenceManager pm = JDODatastore.getPersistenceManager();
        try
        {
           Query query = pm.newQuery(Team.class);
                  
            logger.fine("Executing Query");
            @SuppressWarnings("unchecked")
            Collection<Team> teams = 
                (Collection<Team>) query.execute();  
            Set<Team> teamSet = new TreeSet<Team>(); 
            logger.fine("Detaching Teams:" + teams.size());           
            for (Team team: teams)
            {
                teamSet.add(pm.detachCopy(team));
            }
            logger.fine("Done get Teams");
            return teamSet;
        }
        finally
        {
            pm.close();
        }        
    }
}
